package com.specter.serv.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.specter.mvc.model.Response;
import com.specter.serv.service.UserOauthService;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 接口认证服务
 * 
 * @author Liang.Wang
 * @since 2025-04-01 09:05:01
 */
@RestController
@RequestMapping("/sure/oauth")
public class OAuth2Controller {

	@Autowired
	private UserOauthService oAuthService;

	/**
	 * <b style="color:red;">client_id 和 client_secret 需要通过开发平台进行注册</b><br/>
	 * 通过client_id 和 client_secret 来获取 access_token
	 * 
	 * @param request 请求
	 * @return 鉴权令牌
	 */
	@RequestMapping("/access_token")
	public HttpEntity<?> accessToken(HttpServletRequest request) {
		try {
			// 构建OAuth请求
			String clientId = request.getParameter("client_id");
			// 检查提交的客户端标识是否正确
			if (!oAuthService.validateClientId(clientId)) {
				String body = "{\"error\":\"invalid_client\",\"error_description\":\"The client's secret is wrong or the ip is wrong, please check it!\"}";
				return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Response.failure("客户端未校验").data(body));
			}

			// 检查客户端安全签名/密钥是否正确（短路算法：优先第一个）
			if (!oAuthService.validateClientSg(request.getParameter("signature"), request.getParameter("timestamp")) && !oAuthService.validateClientSk(request.getParameter("client_secret"))) {
				String body = "{\"error\":\"unauthorized_client\",\"error_description\":\"The client's secret is wrong or the ip is wrong, please check it!\"}";
				return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Response.failure("客户端未认证").data(body));
			}

			// 检查验证类型，此处只检查AUTHORIZATION_CODE类型，其他的还有PASSWORD或REFRESH_TOKEN
			if ("authorization_code".equals(request.getParameter("grant_type"))) {
				String authCode = request.getParameter("code");
				if (!oAuthService.validateAuthCode(authCode)) {
					String body = "{\"error\":\"invalid_grant\",\"error_description\":\"The authorization_code is wrong or the ip is wrong!\"}";
					return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Response.failure("授权码未校验").data(body));
				}
				clientId = oAuthService.getByAuthCode(authCode);
			}

			// 生成Access Token
			final String accessToken = oAuthService.addAccessToken(clientId);

			// 生成OAuth响应
			String body = "{\"access_token\":\"" + accessToken + "\",\"expires_in\":\"" + oAuthService.getExpireIn() + "\"}";
			// 根据OAuthResponse生成ResponseEntity
			return ResponseEntity.ok(Response.success().data(body));

		} catch (Exception e) {
			e.printStackTrace();
			// 构建错误响应
			String body = "{\"error\":\"" + e.getMessage() + "\",\"error_description\":\"There is an error !!!\"}";
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Response.failure("server_exception").data(body));
		}
	}

	/**
	 * 验证accessToken
	 * 
	 * @param accessToken
	 * @return 验证的结果
	 */
	@RequestMapping("/valid_token")
	public ResponseEntity<?> validateToken(@RequestParam("access_token") String accessToken) {
		boolean b = oAuthService.validateAccessToken(accessToken);
		return b ? ResponseEntity.ok(Response.success()): ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Response.failure("invalid_token"));
	}
}
